// 封装axios
import axios from "axios";
import { ElMessage } from 'element-plus'
import { getToken, getUid, isLoggedIn } from '../hooks/auth'
// console.log(vue)
// 使用自定义的配置文件发送请求
const instance = axios.create({
  baseURL: "",
  timeout: 80000,
  headers: {
    "Content-Type": "application/json;charset=UTF-8"
    // 'custome-header':'tianliangjiaoyu'
  }
});
// post请求的时候，我们需要加上一个请求头，所以可以在这里进行一个默认的设置，即设置post的请求头为
axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";
// 添加请求拦截器
instance.interceptors.request.use(
  (config: any) => {
    //请求拦截器
    if (config.method == 'post') {
      if (!isLoggedIn()) {
        return Promise.reject({ code: 1001, msg: "未登录" })
      }
      config.data.app_key = "KDMspoww"
      config.data.app_secret = "e97ae8b1238cd57c3cd5576289fba674f533cbe2"
      config.data.auth_token = getToken()
      if (!config.data.channel) {
        config.data.channel = "ArtScpeAi"
      }
      if (!config.data.channel_id) {
        config.data.channel_id = 6
      }
      if (!config.data.uid) {
        config.data.uid = getUid()
      }
    }
    return config;
  },
  (error: any) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  (response: any) => {
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      ElMessage.error(response);
      return Promise.reject(response);
    }
  },
  (error: any) => {
    // 对响应错误做点什么
    return Promise.resolve(error.data = error);
  }
);

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url: any, params: any) {
  return new Promise((resolve, reject) => {
    instance
      .get(url, {
        params: params
      })
      .then((res: any) => {
        resolve(res.data);
      })
      .catch((err: any) => {
        reject(err.data);
      });
  });
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url: any, params: any, headers: any) {
  if (!params) params = {}
  // console.log(params, headers);
  return new Promise((resolve, reject) => {
    instance
      .post(url, params, headers)
      .then((res: any) => {
        resolve(res.data);
      })
      .catch((err: any) => {
        reject(err.data);
      });
  });
}
export function fanyiPost(url: any, params: any, headers: any) {

  return new Promise((resolve, reject) => {
    instance
      .post(url, params, headers)
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data);
      });
  });
}